#include "TrFollowTrader.h"
#include <QDomDocument>

//==================================================
extern std::shared_ptr<CTrManager> g_pManager;
//==================================================

CTrFollowTrader::CTrFollowTrader() :
    m_Lots(1),
    m_Offset(0)
{
    g_pManager->TrAddReceiver(this);
    LoadXmlFollowConfig();
}

CTrFollowTrader::~CTrFollowTrader()
{
    g_pManager->TrDelReceiver(this);
}

void CTrFollowTrader::OnReceiveData(Tr_ResponseID rId, void* wParam, void* lParam)
{
    Q_UNUSED(lParam);
    switch (rId)
    {
    case Tr_ResponseID::TrOnRtnOrder:
    {
        CThostFtdcTradeField *pTrade = reinterpret_cast<CThostFtdcTradeField *>(wParam);
        if(m_SourceID == QString::fromLocal8Bit(pTrade->UserID))
        {
            SendTradeMessage(pTrade);
        }
        break;
    }
    default:
        break;
    }
}

void CTrFollowTrader::SendTradeMessage(CThostFtdcTradeField *pTrade)
{
    for(auto i = 0; i < m_TraderID.size(); i++)
    {
        if(m_SourceID != m_TraderID.at(i))
        {
            HWND hWnd = ::FindWindowW(nullptr, QString::fromUtf8("TrServerMainWindow_%1").arg(m_TraderID.at(i)).toStdWString().c_str());
            if(hWnd)
            {
                ::SendMessage(hWnd, MESSAGE_ONTRADE, reinterpret_cast<WPARAM>(pTrade), NULL);
            }
        }
    }
}

void CTrFollowTrader::AddFollowID(QString UserID)
{
    if(!m_TraderID.contains(UserID))
    {
        m_TraderID.append(UserID);
    }
}

void CTrFollowTrader::OnTrade(CThostFtdcTradeField *pTrade)
{
    qDebug() << __FUNCTION__ << pTrade->UserID << m_SourceID << m_TraderID;
}

void CTrFollowTrader::LoadXmlFollowConfig()
{
    QString file = AppPath + "/TrConfigs/FollowTraderConfig.xml";
    QFile xmlfile(file);
    if (!xmlfile.open(QFile::ReadOnly))
    {
        qDebug() << "Error:" << file << "not open ...";
        return;
    }

    QDomDocument doc;
    if (!doc.setContent(&xmlfile))
    {
        xmlfile.close();
        qDebug() << "Error:" << file << "can't read ...";
        return;
    }
    xmlfile.close();

    QDomElement FollowTrader = doc.documentElement();
    QDomNodeList nodeList = FollowTrader.childNodes();

    for(auto i = 0; i < nodeList.count(); i++)
    {
        QDomNode n = nodeList.at(i);
        if(n.isElement())
        {
            if(n.nodeName() == "Accepter")
            {
                m_TraderID.append(n.toElement().text());
            }
            if(n.nodeName() == "TradeSource")
            {
                m_SourceID = n.toElement().text();
            }
            if(n.nodeName() == "InstrumentID")
            {
                m_InstrumentID = n.toElement().text();
            }
            if(n.nodeName() == "Lots")
            {
                m_Lots = n.toElement().text().toInt();
            }
        }
    }
}
